package test00011;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

public class MathExerciseGenerator extends JFrame {
    // 难度级别
    enum Difficulty {
        EASY, MEDIUM, HARD
    }

    // 题目类
    static class Exercise {
        int num1;
        int num2;
        String operator;
        int correctAnswer;
        String question;

        public Exercise(int num1, int num2, String operator, int correctAnswer) {
            this.num1 = num1;
            this.num2 = num2;
            this.operator = operator;
            this.correctAnswer = correctAnswer;
            this.question = num1 + " " + operator + " " + num2 + " = ?";
        }
    }

    // UI组件
    private JComboBox<Difficulty> difficultyComboBox;
    private JSpinner exerciseCountSpinner;
    private JCheckBox additionCheck, subtractionCheck, multiplicationCheck, divisionCheck;
    private JButton generateButton, checkButton, exportButton;
    private JTextArea exerciseArea;
    private JTextArea answerArea;
    private JLabel scoreLabel;

    // 数据
    private ArrayList<Exercise> exercises;
    private int currentExercise = 0;
    private int score = 0;

    public MathExerciseGenerator() {
        setTitle("小学生数学练习题生成系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 初始化组件
        initComponents();

        // 添加组件到面板
        add(createControlPanel(), BorderLayout.NORTH);
        add(createExercisePanel(), BorderLayout.CENTER);
        add(createResultPanel(), BorderLayout.SOUTH);

        setVisible(true);
    }

    private void initComponents() {
        // 难度选择
        difficultyComboBox = new JComboBox<>(Difficulty.values());

        // 题目数量
        SpinnerNumberModel spinnerModel = new SpinnerNumberModel(10, 1, 50, 1);
        exerciseCountSpinner = new JSpinner(spinnerModel);

        // 运算类型
        additionCheck = new JCheckBox("加法", true);
        subtractionCheck = new JCheckBox("减法", true);
        multiplicationCheck = new JCheckBox("乘法", false);
        divisionCheck = new JCheckBox("除法", false);

        // 按钮
        generateButton = new JButton("生成题目");
        checkButton = new JButton("检查答案");
        exportButton = new JButton("导出题目");

        // 文本区域
        exerciseArea = new JTextArea();
        exerciseArea.setEditable(false);
        exerciseArea.setFont(new Font("宋体", Font.PLAIN, 18));

        answerArea = new JTextArea();
        answerArea.setFont(new Font("宋体", Font.PLAIN, 18));

        // 分数标签
        scoreLabel = new JLabel("得分: 0/0");
        scoreLabel.setFont(new Font("宋体", Font.BOLD, 16));

        // 添加事件监听
        generateButton.addActionListener(e -> generateExercises());
        checkButton.addActionListener(e -> checkAnswers());
        exportButton.addActionListener(e -> exportExercises());
    }

    private void exportExercises() {
    }

    private JPanel createControlPanel() {
        JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
        panel.setBorder(BorderFactory.createTitledBorder("设置"));

        JPanel difficultyPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        difficultyPanel.add(new JLabel("难度级别:"));
        difficultyPanel.add(difficultyComboBox);

        JPanel countPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        countPanel.add(new JLabel("题目数量:"));
        countPanel.add(exerciseCountSpinner);

        JPanel operationPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        operationPanel.add(new JLabel("运算类型:"));
        operationPanel.add(additionCheck);
        operationPanel.add(subtractionCheck);
        operationPanel.add(multiplicationCheck);
        operationPanel.add(divisionCheck);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(generateButton);
        buttonPanel.add(checkButton);
        buttonPanel.add(exportButton);

        panel.add(difficultyPanel);
        panel.add(countPanel);
        panel.add(operationPanel);
        panel.add(buttonPanel);

        return panel;
    }

    private JPanel createExercisePanel() {
        JPanel panel = new JPanel(new GridLayout(1, 2, 10, 10));
        panel.setBorder(BorderFactory.createTitledBorder("练习题"));

        JScrollPane exerciseScroll = new JScrollPane(exerciseArea);
        exerciseScroll.setBorder(BorderFactory.createTitledBorder("题目"));

        JScrollPane answerScroll = new JScrollPane(answerArea);
        answerScroll.setBorder(BorderFactory.createTitledBorder("答案 (每行一个)"));

        panel.add(exerciseScroll);
        panel.add(answerScroll);

        return panel;
    }

    private JPanel createResultPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("结果"));
        panel.add(scoreLabel, BorderLayout.CENTER);
        return panel;
    }

    private void generateExercises() {
        int count = (Integer) exerciseCountSpinner.getValue();
        Difficulty difficulty = (Difficulty) difficultyComboBox.getSelectedItem();

        // 检查至少选择了一种运算
        if (!additionCheck.isSelected() && !subtractionCheck.isSelected() &&
                !multiplicationCheck.isSelected() && !divisionCheck.isSelected()) {
            JOptionPane.showMessageDialog(this, "请至少选择一种运算类型！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        exercises = new ArrayList<>();
        Random random = new Random();
        StringBuilder exerciseText = new StringBuilder();

        for (int i = 0; i < count; i++) {
            String operator = getRandomOperator();
            int num1, num2;
            int result = 0;

            // 根据难度设置数字范围
            switch (difficulty) {
                case EASY:
                    num1 = random.nextInt(20) + 1; // 1-20
                    num2 = random.nextInt(10) + 1; // 1-10
                    break;
                case MEDIUM:
                    num1 = random.nextInt(50) + 1; // 1-50
                    num2 = random.nextInt(20) + 1; // 1-20
                    break;
                case HARD:
                    num1 = random.nextInt(100) + 1; // 1-100
                    num2 = random.nextInt(50) + 1; // 1-50
                    break;
                default:
                    num1 = random.nextInt(20) + 1;
                    num2 = random.nextInt(10) + 1;
            }

            // 确保减法结果非负
            if (operator.equals("-") && num1 < num2) {
                int temp = num1;
                num1 = num2;
                num2 = temp;
            }

            // 确保除法能整除
            if (operator.equals("/")) {
                while (num2 == 0) num2 = random.nextInt(10) + 1;
                int divisor = num2;
                num2 = num1 * divisor;
                int temp = num1;
                num1 = num2;
                num2 = temp;
            }

            // 计算结果
            switch (operator) {
                case "+":
                    result = num1 + num2;
                    break;
                case "-":
                    result = num1 - num2;
                    break;
                case "*":
                    result = num1 * num2;
                    break;
                case "/":
                    result = num1 / num2;
                    break;
            }

            Exercise exercise = new Exercise(num1, num2, operator, result);
            exercises.add(exercise);

            exerciseText.append(i + 1).append(". ").append(exercise.question).append("\n");
        }

        exerciseArea.setText(exerciseText.toString());
        answerArea.setText("");
        currentExercise = 0;
        score = 0;
        scoreLabel.setText("得分: 0/" + exercises.size());
    }

    private String getRandomOperator() {
        ArrayList<String> operators = new ArrayList<>();

        if (additionCheck.isSelected()) operators.add("+");
        if (subtractionCheck.isSelected()) operators.add("-");
        if (multiplicationCheck.isSelected()) operators.add("*");
        if (divisionCheck.isSelected()) operators.add("/");

        if (operators.isEmpty()) return "+";

        Random random = new Random();
        return operators.get(random.nextInt(operators.size()));
    }

    private void checkAnswers() {
        if (exercises == null || exercises.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请先生成题目！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String[] answers = answerArea.getText().split("\n");
        score = 0;

        if (answers.length != exercises.size()) {
            JOptionPane.showMessageDialog(this, "请完成所有题目后再检查！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < exercises.size(); i++) {
            try {
                int userAnswer = Integer.parseInt(answers[i].trim());
                Exercise exercise = exercises.get(i);

                if (userAnswer == exercise.correctAnswer) {
                    score++;
                    result.append("✓ ");
                } else {
                    result.append("✗ ");
                }

                result.append(exercise.question).append(" 你的答案: ").append(userAnswer)
                        .append(", 正确答案: ").append(exercise.correctAnswer).append("\n");
            } catch (NumberFormatException e) {
                result.append("? 第 ").append(i + 1).append(" 题: 无效答案\n");
            }
        }

        double percentage;
    }
}